package com.vhome.wedding;

import java.sql.SQLException;
import java.util.Locale;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.vhome.beans.User;
import com.vhome.database.dbManager;


/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	public static User currentUser = new User();
	
	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(Locale locale, Model model) {
		return "redirect:/";
	}
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String noneInput(Locale locale, Model model) throws SQLException {
		logger.info("Welcome home! the client locale is "+ locale.toString());
		
		return "index";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(String userId, String password, HttpSession session) throws SQLException {
			
		String lastVisit = (String) session.getAttribute("lastVisit");
		User user = dbManager.login(userId);
		
		session.setAttribute("user", user);
		
		if(user.getPassword() == null) {
			return "error";
		}
		if (user.getPassword().equals(password)) {
			currentUser = user;
			return "redirect:/userView/";
		} else {
			return "error";
		}
	}
	
	@RequestMapping(value = "/userView", method = RequestMethod.GET)
	public String userView(Model model) {
		model.addAttribute("user", currentUser);
		currentUser.getUsername();
		return "userView";
	}
}
